var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//导入express.session
const session = require('express-session')
const MongoStore = require('connect-mongo')

var indexRouter = require('./routes/web/index');
var authRouter = require('./routes/web/auth');
var authApiRouter = require('./routes/api/auth');

// var usersRouter = require('./routes/users');

//导入account 接口路由文件
const accountRouter = require('./routes/api/account');


var app = express();

const{DBHOST,DBNAME,DBPORT}=require('./config/config')

//设置session中间件，此中间件为全局中间件
app.use(session({
  name:'sid',//设置cookie的name，默认值是：connect.sid
  secret:'ballball',//参与加密的字符串（签名）
  saveUninitialized:false,//是否为每次请求都设置一个cookie进行存储
  resave:true,//是否在每次请求时都重新保存session
  store:MongoStore.create({
      mongoUrl:`mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
  }),
  cookie:{
      httpOnly:true,//开启后前端无法通过JS操作，一个标识，有了这个标识，浏览器前端就无法通过js对这个cookie进行任何操作（如：控制台document.cookie）
      maxAge:1000*60*60*24//sessionID的过期时间（服务器存储的session。和响应到客户端的cookie的过期时间）
  }
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());//用于将请求体的对象解析为js对象
app.use(express.urlencoded({ extended: false }));//用于将请求体的对象解析为js对象
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/api',accountRouter);
app.use('/',authRouter);
app.use('/api',authApiRouter)

// app.use('/users', usersRouter);

// 404代码的处理
app.use(function(req, res, next) {
  res.render('404');
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
